<template>
  <div>
    <top-bar :total="total" :index="index" :answers-results="answersResults" title="随机练习" @save="save"/>
    <el-card class="random-card">
      <div class="random-gray">
        <h4>
          <span>{{ index + 1 }}.</span> <span>{{ item.title }}</span>
          <img v-show="item.titlePicUrl" :src="version + '/uploadFile/path/' + item.titlePicUrl" alt="titlePicUrl" class="random-pic">
        </h4>
        <div v-show="rightAnswer.length === 1">
          <el-radio-group v-model="checkedAnswer">
            <el-radio :class="status.optiona" label="A" class="random-block" @change="changeAnswer('optiona', 'A')">
              A.
              <span v-show="!isImage(item.optiona)">{{ item.optiona }}</span>
              <img v-show="isImage(item.optiona)" :src="version + '/uploadFile/path/' + item.optiona" alt="optiona" class="random-pic">
            </el-radio>
            <el-radio :class="status.optionb" label="B" class="random-block" @change="changeAnswer('optionb', 'B')">
              B.
              <span v-show="!isImage(item.optionb)">{{ item.optionb }}</span>
              <img v-show="isImage(item.optionb)" :src="version + '/uploadFile/path/' + item.optionb" alt="optionb" class="random-pic">
            </el-radio>
            <el-radio :class="status.optionc" label="C" class="random-block" @change="changeAnswer('optionc', 'C')">
              C.
              <span v-show="!isImage(item.optionc)">{{ item.optionc }}</span>
              <img v-show="isImage(item.optionc)" :src="version + '/uploadFile/path/' + item.optionc" alt="optionc" class="random-pic">
            </el-radio>
            <el-radio :class="status.optiond" label="D" class="random-block" @change="changeAnswer('optiond', 'D')">
              D.
              <span v-show="!isImage(item.optiond)">{{ item.optiond }}</span>
              <img v-show="isImage(item.optiond)" :src="version + '/uploadFile/path/' + item.optiond" alt="optiond" class="random-pic">
            </el-radio>
            <el-radio v-show="item.optione" :class="status.optione" label="E" class="random-block" @change="changeAnswer('optione', 'E')">
              E.
              <span v-show="!isImage(item.optione)">{{ item.optione }}</span>
              <img v-show="isImage(item.optione)" :src="version + '/uploadFile/path/' + item.optione" alt="optiond" class="random-pic">
            </el-radio>
          </el-radio-group>
        </div>
        <div v-show="rightAnswer.length > 1">
          <el-checkbox-group v-model="checkedAnswers">
            <el-checkbox :class="status.optiona" label="A" class="random-block" @change="changeAnswers('optiona', 'A')">
              A.
              <span v-show="!isImage(item.optiona)">{{ item.optiona }}</span>
              <img v-show="isImage(item.optiona)" :src="version + '/uploadFile/path/' + item.optiona" alt="optiona" class="random-pic">
            </el-checkbox>
            <el-checkbox :class="status.optionb" label="B" class="random-block" @change="changeAnswers('optionb', 'B')">
              B.
              <span v-show="!isImage(item.optionb)">{{ item.optionb }}</span>
              <img v-show="isImage(item.optionb)" :src="version + '/uploadFile/path/' + item.optionb" alt="optionb" class="random-pic">
            </el-checkbox>
            <el-checkbox :class="status.optionc" label="C" class="random-block" @change="changeAnswers('optionc', 'C')">
              C.
              <span v-show="!isImage(item.optionc)">{{ item.optionc }}</span>
              <img v-show="isImage(item.optionc)" :src="version + '/uploadFile/path/' + item.optionc" alt="optionc" class="random-pic">
            </el-checkbox>
            <el-checkbox :class="status.optiond" label="D" class="random-block" @change="changeAnswers('optiond', 'D')">
              D.
              <span v-show="!isImage(item.optiond)">{{ item.optiond }}</span>
              <img v-show="isImage(item.optiond)" :src="version + '/uploadFile/path/' + item.optiond" alt="optiond" class="random-pic">
            </el-checkbox>
            <el-checkbox v-show="item.optione" :class="status.optione" label="E" class="random-block" @change="changeAnswers('optione', 'E')">
              E.
              <span v-show="!isImage(item.optione)">{{ item.optione }}</span>
              <img v-show="isImage(item.optione)" :src="version + '/uploadFile/path/' + item.optione" alt="optiond" class="random-pic">
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="random-answer-show">
          <el-button @click="isShow = !isShow">
            <span v-show="isShow">隐藏答案</span>
            <span v-show="!isShow">显示答案</span>
          </el-button>
        </div>
        <div v-show="isShow" class="random-answer-show">
          <p>正确答案：{{ item.rightAnswer }}</p>
          <p>答案解析：{{ item.answerParse }}</p>
        </div>
      </div>
      <div style="text-align: center; margin-top: 30px">
        <el-button v-show="index !== 0" style="float: left" @click="prev">上一题</el-button>
        <el-button style="display: inline-block; width: 100px; margin: 0 auto">收藏</el-button>
        <el-button v-show="index !== (items.length - 1)" style="float: right" @click="next">下一题</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import TopBar from '@/components/TopBar'
import { VERSION } from '@/constants/uri'
import { resetJson } from '@/utils/reset'
const imageSuffixs = ['png', 'jpg', 'jpeg']
export default {
  name: 'Exercise',
  components: {
    TopBar
  },
  data() {
    return {
      items: [],
      item: {},
      isShow: false,
      // 选过的答案 ['A', 'B,C']
      answers: [],
      // 浏览过的每道题的状态， 是否做对或未做
      answersResults: [],
      // 正确答案
      rightAnswer: [],
      // 单选选择的答案
      checkedAnswer: '',
      // 多选选择的答案
      checkedAnswers: [],
      index: 0,
      version: VERSION,
      status: {
        optiona: '',
        optionb: '',
        optionc: '',
        optiond: '',
        optione: ''
      }
    }
  },
  mounted() {
    this.queryList()
  },
  methods: {
    /*
    *   点击上一题
    * */
    prev() {
      // 判断当前题是否正确  必须在index之前调用
      this.isCorrect()
      this.index--
      this.initAnswer()
    },
    /*
    *   点击下一题
    * */
    next() {
      // 判断当前题是否正确  必须在index之前调用
      this.isCorrect()
      this.index++
      this.initAnswer()
    },
    /*
    *   判断当前题是否正确  必须在index变化之前调用
    * */
    isCorrect() {
      let answerResult = 0
      if (this.rightAnswer.length > 1) {
        if (this.checkedAnswers.length === 0) {
          answerResult = 0
        } else if (this.checkedAnswers.sort().join('') === this.rightAnswer.join('')) {
          answerResult = 1
        } else {
          answerResult = 2
        }
      } else {
        if (this.checkedAnswer === '') {
          answerResult = 0
        } else if (this.checkedAnswer === this.rightAnswer.join('')) {
          answerResult = 1
        } else {
          answerResult = 2
        }
      }
      this.answersResults[this.index] = answerResult
    },
    /*
    *   点击上一题或下一题之后初始化答案等数据
    * */
    initAnswer() {
      this.$emit('getIndex', this.index)
      this.isShow = false
      this.checkedAnswer = ''
      this.checkedAnswers = []
      this.item = this.items[this.index]
      this.rightAnswer = this.item.rightAnswer.split(',')
      // 初始化选中的答案
      resetJson(this.status)
      if (this.item.rightAnswer.split(',').length > 1) {
        this.checkedAnswers = this.answers[this.index] ? this.answers[this.index] : []
        this.initStatus(this.checkedAnswers)
      } else {
        this.checkedAnswer = this.answers[this.index] ? this.answers[this.index] : ''
        this.initStatus(this.checkedAnswer)
      }
    },
    initStatus(checkedAnswers) {
      if (typeof checkedAnswers === 'string') {
        const key = 'option' + checkedAnswers.toLowerCase()
        if (checkedAnswers === this.item.rightAnswer) {
          this.status[key] = 'success'
        } else {
          this.status[key] = 'error'
        }
      } else {
        checkedAnswers.forEach(item => {
          const key = 'option' + item.toLowerCase()
          if (this.item.rightAnswer.includes(item)) {
            this.status[key] = 'success'
          } else {
            this.status[key] = 'error'
          }
        })
      }
    },
    /*
   *   保存进度
   * */
    save() {
      const postData = []
      this.answers.forEach((item, index) => {
        let answerResult = 0
        let type = ''
        if (typeof item === 'string') {
          type = 'string'
          if (item === '') {
            answerResult = 0
          } else if (item === this.items[index].rightAnswer) {
            answerResult = 1
          } else {
            answerResult = 2
          }
        } else {
          type = 'array'
          if (item.length === 0) {
            answerResult = 0
          } else if (item.join(',') === this.items[index].rightAnswer) {
            answerResult = 1
          } else {
            answerResult = 2
          }
        }
        postData.push({
          questId: this.items[index].id,
          result: type === 'string' ? item : item.join(','),
          answerResult: answerResult
        })
      })
      axios.post('/save/doPractice', { data: postData,
        examType: '执业西药师',
        seq: this.index + 1,
        subjectCategoryId: 'all',
        subjectChapterId: 'all'
      }).then(res => {
        if (res.success) {
          alert('success')
        }
      })
    },
    /*
    *   答案是否是图片
    * */
    isImage(value) {
      if (!value) {
        return false
      }
      const index = value.lastIndexOf('.')
      if (!index) {
        return false
      }

      if (imageSuffixs.includes(value.substr(index + 1))) {
        return true
      }
    },
    /*
    *   选中单选题
    * */
    changeAnswer(key, value) {
      this.answers[this.index] = this.checkedAnswer
      if (this.checkedAnswer === value) {
        if (this.rightAnswer.includes(value)) {
          this.status[key] = 'success'
        } else {
          this.status[key] = 'error'
        }
      } else {
        this.status[key] = ''
      }
    },
    /*
    *   多选题选中
    * */
    changeAnswers(key, value) {
      this.answers[this.index] = this.checkedAnswers
      // 选中
      if (this.checkedAnswers.includes(value)) {
        if (this.rightAnswer.includes(value)) {
          this.status[key] = 'success'
        } else {
          this.status[key] = 'error'
        }
      } else {
        this.status[key] = ''
      }
    },
    /*
    *   获取所有题目
    * */
    queryList() {
      axios.get('/random/practice/执业西药师/1/2000').then(res => {
        if (res.success && res.data.length) {
          this.index = res.seq - 1
          this.$emit('getIndex', this.index)
          this.$emit('getTotal', res.total)
          this.items = res.data
          this.item = this.items[this.index]
          this.rightAnswer = this.item.rightAnswer.split(',')
          res.data.forEach(item => {
            if (item.result.length > 1) {
              const checkedAnswers = item.result.split(',')
              this.answers.push(item.result.split(','))
              this.checkedAnswers = checkedAnswers
              this.initStatus(checkedAnswers)
            } else {
              this.answers.push(item.result)
              this.checkedAnswer = item.result
              this.initStatus(this.checkedAnswer)
            }
            this.answersResults.push(item.answerResult)
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
  .random-card {
    margin: 20px;
  }

  .random-block {
    display: block;
    margin: 10px 0 25px 0 !important;
  }

  .random-pic {
    width: 150px;
    margin-left: 20px;
    vertical-align: middle;
  }

  .success {
    .el-checkbox__input.is-checked+.el-checkbox__label, .el-radio__input.is-checked+.el-radio__label {
      color: green;
    }
  }

  .error {
    .el-checkbox__input.is-checked+.el-checkbox__label, .el-radio__input.is-checked+.el-radio__label {
      color: red;
    }
  }

  .random-answer-show {
    margin-bottom: 30px;
  }
  .random-gray {
    padding: 10px;
    background: #f0f2f5;
  }
</style>
